package sw6.digipecs.helpers;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;
import android.widget.Toast;

// Code example used: http://www.codeshogun.com/blog/2009/04/17/how-to-detect-shake-motion-in-android-part-i/

public class ShakeDetecter implements SensorEventListener {

	private static final int SHAKE_THRESHOLD = 800;
	private long lastUpdate;
	private float last_x, last_y, last_z;
	private Context mContext;
	private Toast toast;
	
	public ShakeDetecter(Context context) {
		mContext = context;
		toast = Toast.makeText(mContext, "Yeah, shake me :)", Toast.LENGTH_SHORT); 
	}
	
	private void show() {
		toast.show();
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		int sensor = event.sensor.getType();
		float[] values = event.values;
		float x,y,z;
		
		if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
			long curTime = System.currentTimeMillis();
			
			// Only allow one update every 100ms.
			if ((curTime - lastUpdate) > 100) {
				long diffTime = (curTime - lastUpdate);
				lastUpdate = curTime;

				x = values[SensorManager.DATA_X];
				y = values[SensorManager.DATA_Y];
				z = values[SensorManager.DATA_Z];

				float speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;

				if (speed > SHAKE_THRESHOLD) {
					Log.d("sw6", "shake detected w/ speed: " + speed);
					show();
				}
				
				last_x = x;
				last_y = y;
				last_z = z;
			}
		}
	}

}
